<template>
    <div>
      <!-- 搜索栏和操作按钮 -->
      <div class="topfunction">
        <el-input
          v-model="searchQuery"
          placeholder="请输入科室、医生搜索"
          clearable
          style="width: 200px;"
        />
        <el-button  class="custom-button" @click="handleAdd()">查询</el-button>
      </div>
  
      <!-- 表格 -->
      <el-table
        :data="currentPageData"
        height="690"
        border
        style="width: 100%"
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column prop="paymentId" label="#" width="50" />
        <el-table-column prop="patientId" label="病人姓名" width="180" />
        <el-table-column prop="paymentMethod" label="支付方式" width="180" />
        <el-table-column prop="amount" label="数量" />
        <el-table-column prop="paymentTime" label="支付时间" />
        <el-table-column prop="status" label="就诊状态" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button  class="custom-button"@click="editRow(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredData.length"
          @current-change="handlePageChange"
          layout="prev, pager, next"
          class="custom-pagination"
        />
      </div>
  
      <!-- 弹窗：新增/编辑 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '预约信息' : '新增信息'"
        width="400px"
      >
        <el-form :model="use4" label-width="80px">
          <el-form-item label="日期">
            {{ use4.date }}
            <!-- <el-input v-model="formData.date" /> -->
          </el-form-item>
          <el-form-item label="价格">
            <!-- <el-input  :rows="5"  v-model="formData.address" /> -->
             {{ use4.price }}
          </el-form-item>
          <el-button type="primary" @click="juni1()" style="margin-left: 75%;" v-if="use4.state2">删除记录</el-button> 
        </el-form>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts">
  import { reactive, ref, computed, onMounted } from "vue";
  import type { Doctor } from "@/type/doctor";
  import axios from 'axios';
  export default {
    setup() {
      
      const doctors = ref<Doctor[]>([]);
      
      const tableData = reactive([
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        // 继续添加更多数据...
      ]);
      let weww=ref("");
      let leng=0;
      const dialogVisible = ref(false);
      const detailDialogVisible = ref(false);
      const formData = reactive({ date: "", name: "", address: "" });
      const selectedRow = ref(null);
      const searchQuery = ref("");
      const isEditing = ref(false);
      // let res=reactive({ appointmentId: "", appointmentTime: "", doctorId: "" ,patientId:"",paymentStatus: "" ,status:""});
      let res={};
      const currentPage = ref(1); // 当前页码
      const pageSize = ref(13); // 每页显示条数
      let use4=reactive({ 
        doctorId: "",
        price:"¥22.00",
        specialty: "",
        state:"未缴费",
        state2:Boolean(0),
        state3:"未就诊",
        date:"2025-01-09 16:03:00",
      });
      interface DataItem {
        paymentId: string;
        patientId: string;
        paymentMethod: string;
        paymentTime: string;
        amount: string;
        status: string;
  }
      let data01=ref<DataItem[]>([
        
        ]);
        
      const filteredData = computed(() => {
    return data01.value.filter(
      (item) =>
        item.paymentMethod.includes(searchQuery.value) ||  // 根据需要调整筛选字段
        item.status.includes(searchQuery.value)
    );
  });
  
  const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredData.value.slice(start, end);
  });
      const handleAdd = () => {
        console.log(searchQuery)
      };
  
      const editRow = (row:any) => {
        isEditing.value = true;
        Object.assign(formData, row);
        console.log(row.specialty);
        use4.specialty=row.specialty;
        use4.doctorId=row.doctorId;
        use4.state2=true;
        localStorage.setItem('username5', row.paymentId);
        dialogVisible.value = true;
      };
      const saveData = () => {
    // 确保 selectedRow.value 和 formData 都是有效的
    if (isEditing.value) {
      const selectedItem = tableData.find((item) => item === selectedRow.value);
      if (selectedItem && formData) {
        // 确保找到的 item 和 formData 都是有效对象
        Object.assign(selectedItem, formData);
      } else {
        console.error("无法更新数据，未找到选中的项或表单数据无效");
      }
    } else {
      if (formData) {
        // 确保 formData 是有效对象
        tableData.push({ ...formData });
      } else {
        console.error("无法添加数据，表单数据无效");
      }
    }
  
    // 隐藏对话框
    dialogVisible.value = false;
  };
  
  const juni1 = () => {
          const wei = localStorage.getItem('username5');
        let id: number = parseInt(wei ?? "0");  // 使用 "0" 作为默认值，避免 wei 为 null 时出现错误
              axios.delete(`http://zhsj.autumnclouds.cn/payment/${id}`)
        .then((response) => {       
          console.log(response.data);
          alert("删除成功!");
        })
        .catch((error) => {
          console.error("删除失败:", error);
          // 你可以根据需要添加错误提示
        });
        
  
  
  };
  const juni2 = () => {
    if(use4.state2==false){
            alert("此时间段已经被预约,请选择其他时间段!");
            return;
          }
          const wei = localStorage.getItem('username2');
          let intWei: number = parseInt(wei ?? "0");  // 使用 "0" 作为默认值，避免 wei 为 null 时出现错误
          console.log(intWei);
          let user2={
            appointmentId: 1,
            patientId: intWei,
            doctorId: use4.doctorId,
            appointmentTime: use4.date,
            status: use4.state3,
            paymentStatus: use4.state,
          }
          console.log(user2);
          axios.post("http://zhsj.autumnclouds.cn/appointment", user2)
              .then((response) => {       
                console.log(response.data.data);
                alert("预约成功,请尽快完成挂号缴费!");
              })
              .catch((error) => {
                alert("预约失败☹️,请勿重复预约");
              });
  };
      const handleDelete = () => {
        if (selectedRow.value) {
          const index = tableData.indexOf(selectedRow.value);
          if (index !== -1) {
            tableData.splice(index, 1);
          }
          selectedRow.value = null;
          // 确保当前页仍有数据
          if ((currentPage.value - 1) * pageSize.value >= filteredData.value.length) {
            currentPage.value = Math.max(1, currentPage.value - 1);
          }
        }
      };
  
       const viewDetails = (row:any) => {
         selectedRow.value = row;
        //  detailDialogVisible.value = true;
       };
  
      const handleRowClick = (row:any) => {
        selectedRow.value = row;
        if(dialogVisible.value==false){
          detailDialogVisible.value = true;
        }
        
        console.log("点击一行元素");
      };
  
      const handlePageChange = (page:any) => {
        currentPage.value = page;
      };
      
      
      let token="";
      onMounted(() => {
        const wei2 = localStorage.getItem('username1');
        console.log(JSON.stringify(wei2));
        const wei = localStorage.getItem('username2');
        let paymentId: number = parseInt(wei ?? "0");  
        const wei3 = localStorage.getItem('username3');
          console.log(JSON.stringify(wei3));
        console.log(paymentId)
            axios.get(`http://zhsj.autumnclouds.cn/payment/patient/${paymentId}`,{
                        headers: {
              'Authorization': `Bearer ${token}`,
            },
            })
              .then((response) => {
                console.log('支付信息:', response.data.data);
                for(let i=0;i<response.data.data.length;i++){
                response.data.data[i].patientId=JSON.stringify(wei3);
                // response.data.data[i].doctorId=response.data.data[response.data.data[i].doctorId-1].name;
              }
                data01.value=response.data.data;
              })
              .catch((error) => {
                console.error('获取支付信息失败:', error);
              });

      });
    
  
  
      return {
        leng,
        res,
        use4,
        tableData,
        dialogVisible,
        detailDialogVisible,
        formData,
        selectedRow,
        searchQuery,
        filteredData,
        currentPage,
        pageSize,
        currentPageData,
        handleAdd,
        handleDelete,
        editRow,
        viewDetails,
        saveData,
        handleRowClick,
        handlePageChange,
        isEditing,
        juni1,
        juni2,
      };
    },
  };
  </script>
  
  <style scoped>
  .el-input {
    margin-right: 10px;
  }
  
  .el-dialog {
    padding: 20px;
  }
  .topfunction{
    display: flex;
    align-items: right;
    margin-top: 10px;
    margin-bottom: 10px;
    margin-right: 20px;
    width: 100%;
    justify-content: flex-end; /* 靠右排列 */
  }
  .custom-button {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 渐变背景 */
    border: none;
    color: #fff;
    font-weight: bold;
    padding: 10px 20px;
    border-radius: 8px; /* 圆角按钮 */
    cursor: pointer;
    transition: all 0.3s ease; /* 动态过渡效果 */
  }
  
  .custom-button:hover {
    transform: scale(1.05); /* 鼠标悬停时放大 */
    box-shadow: 0 4px 10px rgba(116, 235, 213, 0.5); /* 光影效果 */
  }
  
  .custom-button:active {
    transform: scale(0.98); /* 点击时微微缩小 */
    box-shadow: none;
  }
  
  .custom-button:disabled {
    background: #e0e0e0; /* 禁用状态颜色 */
    color: #aaa;
    cursor: not-allowed;
    box-shadow: none;
  }
  
  .danger-button {
    background: linear-gradient(90deg, #acb6e5, #ff7272); /* 危险操作渐变色 */
  }
  
  .danger-button:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 10px rgba(255, 114, 114, 0.5); /* 特殊危险操作光影 */
  }
  /* 分页容器样式：居中对齐 */
  .pagination-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    margin-top: 20px; /* 与内容分隔距离 */
    gap: 12px; /* 分页按钮间距 */
  }
  
  /* 自定义分页主题样式 */
  .custom-pagination ::v-deep(.el-pager li) {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 主体渐变背景 */
    border: 1px solid #acb6e5; /* 边框 */
    color: #fff; /* 字体颜色 */
    border-radius: 4px; /* 圆角 */
    transition: all 0.3s ease; /* 平滑过渡 */
    margin: 0 8px; /* 增加间距 */
    padding: 8px 16px; /* 增加点击区域 */
  }
  
  /* 鼠标悬停时 */
  .custom-pagination ::v-deep(.el-pager li:hover) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 鼠标悬停反转渐变 */
    box-shadow: 0 6px 12px rgba(116, 235, 213, 0.4); /* 更显著的光影效果 */
  }
  
  /* 激活状态：选中当前页 */
  .custom-pagination ::v-deep(.el-pager li.is-active) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 加深颜色效果 */
    font-weight: bold; /* 加粗字体 */
    font-size: 1.1em; /* 略微增加字体大小 */
    color: #fff;
    border: 1px solid #74ebd5; /* 使用主题色作为边框 */
    box-shadow: 0 6px 14px rgba(116, 235, 213, 0.5); /* 增强光影 */
    transform: scale(1.1); /* 放大以凸显效果 */
  }
  
  /* 分页导航按钮：上一页/下一页 */
  .custom-pagination ::v-deep(.el-pagination__prev, .el-pagination__next) {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 渐变背景 */
    color: #fff; /* 字体颜色 */
    border-radius: 4px; /* 圆角 */
    padding: 8px 16px; /* 按钮尺寸 */
    margin: 0 8px; /* 导航按钮之间的间隔 */
    transition: all 0.3s ease;
    border: 1px solid #acb6e5;
  }
  
  /* 鼠标悬停时（上一页/下一页） */
  .custom-pagination ::v-deep(.el-pagination__prev:hover, .el-pagination__next:hover) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 悬停渐变 */
    box-shadow: 0 6px 10px rgba(172, 182, 229, 0.3); /* 光影效果 */
  }
  
  /* 禁用状态 */
  .custom-pagination ::v-deep(.is-disabled) {
    background: #e0e0e0; /* 灰色背景 */
    color: #aaa; /* 禁用状态字体颜色 */
    cursor: not-allowed;
    box-shadow: none;
  }
  </style>